import { PageContainer } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Table, message, PaginationProps, Modal, Form, Input, Select, Popconfirm, InputNumber } from 'antd';
import type { TableColumnsType, FormProps, FormInstance } from 'antd';
import { getLevelList, getLevelAdd, getLevelEdit, getLevelDelete } from '@/api/staff';
import React, { useState, useEffect, useMemo, useRef } from 'react';
import './base.css';

// 档级接口定义 - 扩展以支持树形结构
export interface LevelItem {
  id: string;
  title: string;
  money: string; // 注意：API返回的是字符串类型
  safe: string;
  station: string;
  between: string;
  performance: string;
  pid: string | number | null; // 父级ID，可能是数字、字符串或null
  children?: LevelItem[]; // 子节点
}

// 树形结构节点接口
export interface TreeNode {
  title: string;
  value: string;
  money?: number; // 岗位工资
  children?: TreeNode[];
  pid: string | number | null; // 保留父级ID用于判断
  [key: string]: any; // 允许其他属性
}

const Welcome: React.FC = () => {
  const [levelList, setLevelList] = useState<LevelItem[]>([]);
  const [total, setTotal] = useState<number>(0); // 数据总数
  const [currentPage, setCurrentPage] = useState<number>(1); // 当前页码
  const [pageSize, setPageSize] = useState<number>(10); // 每页条数
  const [isModalVisible, setIsModalVisible] = useState(false); // 控制弹窗显示隐藏
  const [isEdit, setIsEdit] = useState(false); // 判断是新增还是编辑
  const [currentRecord, setCurrentRecord] = useState<LevelItem | null>(null); // 编辑时的当前记录
  const [parentOptions, setParentOptions] = useState<{ value: string | number; label: string }[]>([]); // 上级选项
  const formRef = useRef<FormInstance<LevelItem>>(); // Form 引用，用于获取表单值

  // 递归函数：将扁平的档级数据转换为树形结构
  const buildLevelTree = (items: LevelItem[]): TreeNode[] => {
    if (!items || items.length === 0) {
      return [];
    }

    // 将所有项转换为TreeNode格式
    const nodeMap: Record<string, TreeNode> = {};
    items.forEach((item) => {
      nodeMap[item.id] = {
        title: item.title,
        value: String(item.id),
        money: parseFloat(item.money) || 0,
        safe: item.safe,
        station: item.station,
        between: item.between,
        performance: item.performance,
        pid: item.pid, // 保留父级ID
        ...item,
      };
    });

    // 构建树形结构
    const tree: TreeNode[] = [];
    items.forEach((item) => {
      const node = nodeMap[item.id];
      const parentId = item.pid;

      // 如果是根节点 (pid为0、"0"或null)
      if (!parentId || parentId === 0 || parentId === '0') {
        tree.push(node);
      } else {
        // 如果有父节点，则添加到父节点的children中
        const parentNodeId = String(parentId);
        if (nodeMap[parentNodeId]) {
          if (!nodeMap[parentNodeId].children) {
            nodeMap[parentNodeId].children = [];
          }
          nodeMap[parentNodeId].children!.push(node);
        } else {
          // 父节点不存在时，作为根节点处理
          tree.push(node);
        }
      }
    });
    return tree;
  };

  // 分页处理：根据当前页码和每页条数截取数据（实际项目需接口支持分页）
  const paginatedTreeData = useMemo(() => {
    if (levelList.length === 0) return [];
    // 1. 先转换完整树形数据
    const fullTree = buildLevelTree(levelList);
    // 2. 分页截取（注：树形数据分页需特殊处理，此处简化为“根节点分页”，子节点随父节点展示）
    const startIndex = (currentPage - 1) * pageSize;
    const endIndex = startIndex + pageSize;
    return fullTree.slice(startIndex, endIndex);
  }, [levelList, currentPage, pageSize]);

  // 获取档级列表（支持分页参数，实际项目需传currentPage和pageSize到接口）
  const fetchLevelList = async () => {
    try {
      // 实际项目：传递分页参数给接口，获取当前页数据和总条数
      const res: any = await getLevelList({
        current: currentPage,
        pageSize: pageSize,
      });

      if (res && res.list && res.list.length >= 0) {
        setLevelList(res.list);
        setTotal(res.total || 0); // 接口返回总条数（如无则用模拟值）
        // 处理上级选项
        const options = res.list
          .filter((item: LevelItem) => !item.pid || item.pid === 0 || item.pid === '0')
          .map((item: LevelItem) => ({
            value: item.id,
            label: item.title,
          }));
        setParentOptions([{ value: 0, label: '顶级' }, ...options]);
      } else {
        setLevelList([]);
        setTotal(0);
        setParentOptions([{ value: 0, label: '顶级' }]);
      }
    } catch (error) {
      console.error('获取档级列表失败:', error);
      message.error('获取档级列表失败');
      setLevelList([]);
      setTotal(0);
      setParentOptions([{ value: 0, label: '请选择' }]);
    }
  };

  // 页码/每页条数变化时重新请求数据
  useEffect(() => {
    fetchLevelList();
  }, [currentPage, pageSize]);

  // 初始化加载数据
  useEffect(() => {
    fetchLevelList();
  }, []);

  const { initialState } = useModel('@@initialState');

  // 定义与树形数据匹配的表格数据类型
  interface DataType {
    key: React.Key;
    title: string;
    money: number;
    safe: string;
    station: string;
    between: string;
    performance: string;
    id: string;
    pid: string | number | null; // 用于判断是否为子节点
    children?: DataType[];
  }

  // 分页配置：支持条数选择、指定页跳转、总数显示
  const paginationConfig: PaginationProps = {
    current: currentPage, // 当前页码
    pageSize: pageSize, // 每页条数
    total: total, // 数据总数
    showSizeChanger: true, // 显示“每页条数”选择器
    showQuickJumper: true, // 显示“指定页跳转”输入框
    showTotal: (total) => `共 ${total} 条数据`, // 显示总数文案
    pageSizeOptions: ['5', '10', '20', '50'], // 每页条数可选值
    // 页码变化回调
    onChange: (page) => {
      setCurrentPage(page);
    },
    // 每页条数变化回调
    onShowSizeChange: (current, size) => {
      setCurrentPage(1); // 条数变化时重置到第1页
      setPageSize(size);
    },
  };

  // 处理删除
  const handleDelete = async (id: string) => {
    try {
      await getLevelDelete({ id });
      message.success('删除成功');
      fetchLevelList();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  // 处理新增
  const handleAdd = async (values: LevelItem) => {
    try {
      await getLevelAdd(values);
      message.success('新增成功');
      setIsModalVisible(false);
      fetchLevelList();
    } catch (error) {
      console.error('新增失败:', error);
      message.error('新增失败');
    }
  };

  // 处理编辑
  const handleEdit = async (values: LevelItem) => {
    if (currentRecord) {
      try {
        await getLevelEdit({
          id: currentRecord.id,
          ...values,
        });
        message.success('编辑成功');
        setIsModalVisible(false);
        fetchLevelList();
      } catch (error) {
        console.error('编辑失败:', error);
        message.error('编辑失败');
      }
    }
  };

  // 表单提交
  const handleOk = () => {
    formRef.current?.validateFields().then((values) => {
      if (isEdit) {
        handleEdit(values);
      } else {
        handleAdd(values);
      }
    });
  };

  const columns: TableColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      render: (text, record) => {
        const isParent = !record.pid || record.pid === 0 || record.pid === '0';
        return isParent ? '' : record.id;
      },
    },
    { title: '档级名称', dataIndex: 'title', key: 'title', align: 'center' },
    { title: '岗位薪资', dataIndex: 'money', key: 'money', align: 'center' },
    { title: '安全质量奖', dataIndex: 'safe', key: 'safe', align: 'center' },
    { title: '岗位津贴', dataIndex: 'station', key: 'station', align: 'center' },
    { title: '薪资区间', dataIndex: 'between', key: 'between', align: 'center' },
    { title: '绩效薪资', dataIndex: 'performance', key: 'performance', align: 'center' },
    {
      title: '操作',
      align: 'center',
      dataIndex: '',
      key: '操作',
      render: (_, record) => (
        <>
          <Button
            type="primary"
            style={{ marginRight: 8 }}
            onClick={() => {
              setIsEdit(true);
              setCurrentRecord(record);
              setIsModalVisible(true);
              formRef.current?.setFieldsValue({
                pid: record.pid,
                title: record.title,
                money: record.money,
                safe: record.safe,
                station: record.station,
                between: record.between,
                performance: record.performance,
              });
            }}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="primary" danger>
              删除
            </Button>
          </Popconfirm>
        </>
      ),
    },
  ];

  return (
    <PageContainer style={{ backgroundColor: 'white', padding: '16px' }}>
      <Button
        type="primary"
        style={{ marginBottom: 16 }}
        onClick={() => {
          setIsEdit(false);
          setCurrentRecord(null);
          setIsModalVisible(true);
          formRef.current?.resetFields();
        }}
      >
        新增
      </Button>
      <Table<DataType>
        bordered
        columns={columns}
        dataSource={paginatedTreeData} // 分页后的树形数据
        rowKey="value"
        treeDefaultExpandAll // 树形节点默认展开
        pagination={paginationConfig} // 配置分页组件
        scroll={{ x: 'max-content' }} // 可选：横向滚动（避免列挤压）
      />
      <Modal
        title={isEdit ? '编辑档级' : '添加档级'}
        open={isModalVisible}
        onOk={handleOk}
        onCancel={() => setIsModalVisible(false)}
      >
        <Form
          ref={formRef}
          layout="vertical"
          initialValues={{
            pid: 0,
          }}
        >
          <Form.Item
            name="pid"
            label="选择上级"
            rules={[{ required: true, message: '请选择上级' }]}
          >
            <Select options={parentOptions} placeholder="请选择上级" />
          </Form.Item>
          <Form.Item
            name="title"
            label="档级名称"
            rules={[{ required: true, message: '请输入档级名称' }]}
          >
            <Input placeholder='请输入档级名称' />
          </Form.Item>
          <Form.Item
            name="money"
            label="岗位工资"
            rules={[{ required: true, message: '请输入岗位工资' }]}
          >
            <InputNumber min={1} placeholder='请输入岗位工资' style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="safe"
            label="安全质量奖"
            rules={[{ required: true, message: '请输入安全质量奖' }]}
          >
            <InputNumber min={1} placeholder='请输入安全质量奖' style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="station"
            label="岗位津贴"
            rules={[{ required: true, message: '请输入岗位津贴' }]}
          >
            <InputNumber min={1} placeholder='请输入岗位津贴' style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="between"
            label="档级薪资区间"
            rules={[{ required: true, message: '请输入档级薪资区间' }]}
          >
            <InputNumber min={1} placeholder='请输入档级薪资区间' style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            name="performance"
            label="绩效薪资"
            rules={[{ required: true, message: '请输入绩效薪资' }]}
          >
            <InputNumber min={1} placeholder='请输入绩效薪资' style={{ width: '100%' }} />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default Welcome;